//
//  DHTabBarController.m
//  lotteryticket
//
//  Created by DH on 16/4/16.
//  Copyright © 2016年 http://blog.sina.com.cn/dhios All rights reserved.
//

#import "DHTabBarController.h"
#import "DHTabBar.h"
#import "DHNavigationController.h"

@interface DHTabBarController()
@property (nonatomic, weak) DHTabBar *customTabBar;
@end

@implementation DHTabBarController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    for (UIView *child in self.tabBar.subviews) {
        if ([child isKindOfClass:[UIControl class]]) {
            [child removeFromSuperview];
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor redColor];
    [self setupCustomTabBar];
    [self setUpAllChildVC];
}

// 初始化所有的子控制器
- (void)setUpAllChildVC
{
     // PDDGoodsViewController
    // PDDHomeViewController
    // PDDMessageViewController
    // PDDMineViewController
    [self dh_addChildVC:@"PDDHomeViewController" title:@"首页" imageName:@"tab_btn_video_22x22_" selectedImageName:@"tab_btn_video_se_22x22_"];
    [self dh_addChildVC:@"PDDGoodsViewController" title:@"货源" imageName:@"tab_btn_dubbing_22x22_" selectedImageName:@"tab_btn_dubbing_se_22x22_"];
    [self dh_addChildVC:@"PDDMessageViewController" title:@"消息" imageName:@"tab_btn_words_22x22_" selectedImageName:@"tab_btn_words_se_22x22_"];
    [self dh_addChildVC:@"PDDMineViewController" title:@"个人中心" imageName:@"tab_icon_me_23x23_" selectedImageName:@"tab_icon_me_se_23x23_"];
}

- (void)dh_addChildVC:(NSString *)childVCString title:(NSString *)title imageName:(NSString *)imageName selectedImageName:(NSString *)selectedImageName {
    
    UIViewController *childVC = [[NSClassFromString(childVCString) alloc] init];

    DHNavigationController *nav = [[NSClassFromString(@"DHNavigationController") alloc] initWithRootViewController:childVC];
        
    if (imageName) {
        childVC.tabBarItem.image = [UIImage imageNamed:imageName];
    }
    
    if (selectedImageName) {
        childVC.tabBarItem.selectedImage = [UIImage imageNamed:selectedImageName];
    }
    
    if ([title isEqualToString:@"首页"]) {
         childVC.navigationItem.title = @"货天下";
    } else {
        childVC.navigationItem.title = title;
    }
    
    childVC.tabBarItem.title = title;
    [self addChildViewController:nav];
    [self.customTabBar addTabBarBtnWithItem:childVC.tabBarItem];

}


- (void)setupCustomTabBar
{
    DHTabBar *customTabBar = [[DHTabBar alloc] init];
    customTabBar.frame = self.tabBar.bounds;
    [self.tabBar addSubview:customTabBar];
    self.customTabBar = customTabBar;
    __unsafe_unretained DHTabBarController *mySelf = self;
    customTabBar.btnClickHandler = ^(DHTabBar *customTaBar, NSInteger fromIndex, NSInteger toIndex){
        mySelf.selectedIndex = toIndex;
    };
}
@end
